package com.foreverwin.jzymes.framework.exception;

import com.foreverwin.jzymes.framework.base.AjaxResult;
import com.foreverwin.jzymes.framework.util.I18nUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.PrintWriter;
import java.io.StringWriter;

@ControllerAdvice
@ResponseBody
public class DefaultExceptionHandler {

    Logger logger  = LoggerFactory.getLogger( DefaultExceptionHandler.class );


    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult notFount(RuntimeException e)
    {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);
        pw.flush();
        sw.flush();
        logger.error( sw.toString() );
        return AjaxResult.returnError(I18nUtil.getI18nText("system.error") + " :"+ e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e)
    {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);
        pw.flush();
        sw.flush();
        logger.error( sw.toString() );
        return AjaxResult.returnError(I18nUtil.getI18nText("system.error") + " :"+ e.getMessage());
    }
}
